package com.gelpag.base.business.role;

import been.RoleInfo;
import been.UserInfo;
import com.gelpag.base.business.menu.MenuInfo;
import com.gelpag.base.init.InitRedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tools.utils.Common;
import tools.utils.IdWorker;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Autowired
    IdWorker idWorker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    InitRedisService initRedisService;

    Set<String> set_menu_id_list = new HashSet<String>();

    Logger logger = LoggerFactory.getLogger(RoleService.class);

    public List<RoleInfo> getRoleList() {
        return roleMapper.getRoleList();
    }

    public List<MenuInfo> getAuthTree(String role_id) {

        //1.获取所有父级菜单
        List<MenuInfo> menu_list = roleMapper.getChildMenuList("0000", role_id);

        //2.递归查询，将父菜单下的子菜单信息加入
        List<MenuInfo> list = getMenuChildListRecursion(menu_list, role_id);
        return list;
    }

    private List<MenuInfo> getMenuChildListRecursion(List<MenuInfo> menu_list, String role_id) {

        for (int i=0; i<menu_list.size(); i++) {
            //获得每一个menu_id
            String menu_id = menu_list.get(i).getMenu_id();
            //Step1. 获取子菜单列表
            List<MenuInfo> childMenuList = roleMapper.getChildMenuList(menu_id, role_id);
            if (childMenuList != null && childMenuList.size() > 0) {
                //Step2. 若有子菜单，排序并保存到对应的父菜单下
                menu_list.get(i).setChildlist(childMenuList);
                getMenuChildListRecursion(childMenuList, role_id);
            } else {
                //Step3. 如果没有子菜单，获得菜单下的所有的resource
                List<MenuInfo> list = roleMapper.getResourcesByMenuId(menu_id, role_id);
                menu_list.get(i).setChildlist(list);
            }
        }
        return menu_list;
    }

    @Transactional
    public void saveAuthTree(String role_id, String resource_ids) {

        //清除角色对应的menu
        roleMapper.deleRoleMenu(role_id);
        //清除角色对应的url
        roleMapper.deleteRoleResource(role_id);
        //清空set数组
        set_menu_id_list.clear();

        //节点id为空时 不做保存操作
        if (!Common.isNullString(resource_ids)) {
            //解析字符串，获取勾选上的resource_ids
            String[] resource_id_list = resource_ids.split(";");
            List<String> resourceList = new ArrayList<>();
            for (String resource_id : resource_id_list) {
                //保存resource_id信息，保存到sys_resource_role表
                if ("2".equals(resource_id.split("#")[1])) {
                    resourceList.add(resource_id.split("#")[0]);
                    String resource_role_id = idWorker.nextId();
                    roleMapper.insertRoleResource(resource_role_id, role_id, resource_id.split("#")[0]);
                }
                //保存menu_id到set数组
                if ("1".equals(resource_id.split("#")[1])) {
                    set_menu_id_list.add(resource_id.split("#")[0]);
                }
            }

            //根据resource_ids获取对应的所有菜单id
            List<String> resource_menu_id_list = roleMapper.getMenuIdByResourceId(resourceList);
            if (set_menu_id_list != null && set_menu_id_list.size()>0) {
                //将页面选择的没有资源的菜单也放到resource_menu_id_list中，查询它是否也存在上级
                for (String s : set_menu_id_list) {
                    if (resource_menu_id_list == null) {
                        resource_menu_id_list = new ArrayList<String>();
                    }
                    resource_menu_id_list.add(s);
                }
            }

            //递归查询所有的父菜单id信息，并保存到set数组中
            getParentMenuIds(resource_menu_id_list);

            //根据set中的所有menu_id,保存到sys_role_menu表
            for (String menu_id : set_menu_id_list) {
                String resource_role_id = idWorker.nextId();
                roleMapper.insertRoleMenu(resource_role_id, menu_id, role_id);
            }
        }

        //刷新redis
        initRedisService.initRedis(stringRedisTemplate);
    }

    private void getParentMenuIds(List<String> menu_ids) {
        for (String menu_id: menu_ids) {
            set_menu_id_list.add(menu_id);
        }

        List<String> parent_menu_id_list = roleMapper.getParentMenuIdByMenuId(menu_ids);
        if (parent_menu_id_list.size() > 0) {
            getParentMenuIds(parent_menu_id_list);
        }
    }

    @Transactional
    public void saveRole(UserInfo userInfo, RoleInfo roleInfo) {

        String role_id = roleInfo.getRole_id();
        roleInfo.setUp_id(userInfo.getUp_id());
        roleInfo.setUp_date(Common.getSysDate("yyyy-MM-dd HH:mm:ss"));
        roleInfo.setUp_name(userInfo.getUp_name());
        if (Common.isNullString(role_id)) {
            //新增
            roleInfo.setRole_id(idWorker.nextId());
            roleInfo.setOp_id(userInfo.getUser_id());
            roleInfo.setOp_date(Common.getSysDate("yyyy-MM-dd HH:mm:ss"));
            roleInfo.setOp_name(userInfo.getUser_name());
            roleMapper.insertRole(roleInfo);
        } else {
            //修改
            roleMapper.updateRole(roleInfo);
        }
    }

    public void deleteRoleById(String role_id) {
        roleMapper.deleteRoleById(role_id);
    }

    public int countRoleRelation(String role_id) {
        return roleMapper.countRoleRelation(role_id);
    }
}
